package com.sheep.secret.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@Slf4j
public class RepeatedlyReadRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    public RepeatedlyReadRequestWrapper(HttpServletRequest request) throws Exception {
        super(request);
        body = writeBody(request).getBytes();
    }

    private static String writeBody(HttpServletRequest request) throws Exception {
        InputStream inputStream = request.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String msg = "";
        StringBuilder sb = new StringBuilder();
        while ((msg = reader.readLine()) != null) {
            sb.append(msg);
        }
        return sb.toString();
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public boolean isFinished() {
                return byteArrayInputStream.available() == 0;
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
}
